package org.template.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.template.dao.iter.RedisDelegator;
import org.template.dao.iter.RedisDelegatorNoResult;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
/**
 * 
 * @author Lesson
 *
 */
@Repository
public class BaseRedisDao {
	
	private static final Logger  log=LoggerFactory.getLogger(BaseRedisDao.class);
	@Autowired
	private JedisPool redisPool;

	private Jedis getJedis() {
		return redisPool.getResource();
	}

	private void releaseJedisWhatever(Jedis edis) {
		redisPool.returnResource(edis);
	}

	private void releaseBrokenJedisWhatever(Jedis edis) {
		redisPool.returnBrokenResource(edis);
	}
	
	protected  <T> T run(RedisDelegator<T> delegator){
		Jedis redis=null;
		boolean isBroken=false;
		try {
			redis=getJedis();
			if (redis==null) return null;
			return  delegator.execute(redis);
		} catch (Exception e) {
			isBroken=true;
			log.debug(e.getMessage(), e);
		}finally{
			if (redis==null) return  null;
			if(isBroken){
				releaseBrokenJedisWhatever(redis);
			}else{
				releaseJedisWhatever(redis);
			}
		}
		return  null;
	}
	
	protected  void  runNoResult(RedisDelegatorNoResult delegator){
		Jedis redis=null;
		boolean isBroken=false;
		try {
			redis=getJedis();
			if (redis==null) return ;
			  delegator.execute(redis);
		} catch (Exception e) {
			isBroken=true;
			log.debug(e.getMessage(), e);
		}finally{
			if (redis==null) return  ;
			if(isBroken){
				releaseBrokenJedisWhatever(redis);
			}else{
				releaseJedisWhatever(redis);
			}
		}
		return  ;
	}
}
